let tbody = document.querySelector('tbody')
let tfoot = document.querySelector('tfoot')
let arr = JSON.parse(localStorage.getItem('shopArr'))

anew()
function anew() {
  tbody.innerHTML = ''

  if (arr.length!=0) {
    let price = 0
    arr.forEach(ele => {
      tbody.innerHTML += `
      <tr>
      <td class="spimg">
        <img src="${ele.goods_small_logo}" alt="">
      </td>
      <td class="spname">
        <p>${ele.goods_name}</p>
      </td>
      <td>
        ￥${parseInt(ele.goods_price).toFixed(2)}
      </td>
      <td>
        <div class="count">
          <div class="sub" goodsId="${ele.goods_id}">-</div>
          <input type="text" value="${ele.count}">
          <div class="sum" goodsId="${ele.goods_id}">+</div>
        </div>
      </td>
      <td>
        ￥0
      </td>
      <td>
        90
      </td>
      <td class="subtotal">
        ￥${ele.count * ele.goods_price}
      </td>
     <td>
       <a href="javascript:;">收藏</a>
       <span>|</span>
       <a href="javascript:;" class="remove"  goodsId="${ele.goods_id}">移出</a>
     </td>
    </tr>
      `
      price += ele.count * ele.goods_price
    })
    tfoot.querySelector('.price').innerHTML = `
    <p><span>商品总金额：</span><i>￥${price}</i></p>
    <p><span>订单优惠金额：</span><i>￥0</i></p>
    <p><span>总金额：</span><b>￥${price}</b></p>
    `
    localStorage.setItem('shopArr', JSON.stringify(arr))
  } else{
    tbody.innerHTML = '您的购物车是空的，请购买商品！'
    tfoot.querySelector('.price').innerHTML = `
    <p><span>商品总金额：</span><i>￥0</i></p>
    <p><span>订单优惠金额：</span><i>￥0</i></p>
    <p><span>总金额：</span><b>￥0</b></p>
    `
    localStorage.setItem('shopArr', JSON.stringify(arr))
  }
}


tbody.addEventListener('click', function (e) {
  e = e || window.event
  var target = e.target || e.srcElement
  if (target.className == 'sub') {
    let id = target.getAttribute('goodsId')
    arr.forEach(ele => {
      if (ele.goods_id === id) {
        ele.count--
        ele.flag = true
        if (ele.count === 0) {
          ele.count = 1
        }
      }
    })
    anew()
  }
  if (target.className == 'sum') {
    let id = target.getAttribute('goodsId')
    arr.forEach(ele => {
      if (ele.goods_id === id) {
          ele.count++
          ele.flag = true
      }
  })
  anew()
  }

  if (target.className == 'remove') {
    let id = target.getAttribute('goodsId')
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].goods_id == id) {
          arr.splice(i, 1)
          i--
      }
  }
  anew()
  }
})


let empty = document.querySelector('.empty')
empty.addEventListener('click',function(){
    arr = []
    anew()
})